<?php

namespace App\Models\OperationManagement;

use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Database\Eloquent\Model;
use App\Models\OperationManagement\GovenmentDeviceFile;
use Illuminate\Database\Eloquent\SoftDeletes;
use Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;

class GovernmentDevice extends Model
{
    use SoftDeletes;
    use SpatialTrait;
    protected $guarded = ['government_ids'];
    protected $spatialFields = ['location','areas'];

    //查询list
    public function getList($request)
    {
    	$per_page = $request->input('per_page',10);
    	return self::orderBy('id','desc')
                ->with(['governmentCategory','department','employees','files'])
                ->where(function($query) use ($request){
                    //检测当前的请求中是否包含device_name、principal参数
                    $name = $request->input('name', '');//市政名称
                    $type_id = $request->input('type_id','');//负责人id
                    $location = $request->input('location','');
                    if(!empty($name)) {
                        $query->where('name','like','%'.$name.'%');
                    }
                    if(!empty($type_id)) {
                        $query->where('type_id','=',$type_id);
                    }
                    if(!empty($location)) {
                        $location = Point::fromString($location);
                        $query->distance('location', $location, 10);
                    }
                })
                ->paginate($per_page)->toArray();
    }

    public function governmentCategory()
    {
        return $this->belongsTo(\App\Models\OperationManagement\GovernmentDeviceCategory::class,'device_type_id','id')->select('id','name');
    }

    //查询所属部门
    public function department()
    {
        return $this->belongsTo(\App\Models\SystemManagement\Department::class,'department_id','id')->select('id','name');
    }

    //查看负责人
    public function employees()
    {
        return $this->belongsTo(\App\Models\SystemManagement\Employee::class,'principal_id','id')->select('id','name');
    }

    function files()
    {
        return $this->hasMany(GovenmentDeviceFile::class,'government_id')->with('file');
    }
}
